#' @export
make_deontologist_analyses <- function() {

box::use(
  data.table,
  estimatr,
  extrafont[loadfonts],
  patchwork[...],
  ggplot2[...],
  showtext,
  stringr[str_extract, str_detect, str_replace],
  lubridate,
  rio[import],
  gtsummary[as_gt, tbl_cross],
  gtExtras[gt_plt_bar_stack],
  gt[...],
  janitor[clean_names],
  forcats[fct_relevel],
  dplyr[...],
  ./helpers/theme_helpers[conjoint_reshape, plexi, format_si, percent],
  here[here],
  likert[likert],
  data.table[setDT],
  tidyr[pivot_longer],
  modelsummary[modelsummary],
  usethis[ui_done, ui_todo, ui_path, ui_info],
  graphics[par],
  grDevices[cairo_pdf],
  stats[lm, median],
  scales,
  cowplot[plot_grid]
)

loadfonts(device = "win")
loadfonts(device = "pdf")
par(family = "CMU Serif")

ui_todo("Starting cleaning and labelling.")
ui_info("Figures will be in {ui_path('figs/')}, tabs in {ui_path('tabs/')}. Data in {ui_path('data/')}.")
ui_info("Input data is:")
ui_info("{ui_path('data/arms_conjoint.RDS')} - conjoint data")
ui_info("{ui_path('data/open_responses_vignette_lr_ger_fr.xlsx')} - the manual classification of the open responses")
ui_info("{ui_path('data/armsexports_polls.xlsx')} - external arms polls data")

# ---------------------------------------------------------------------------- #
#                          prep data for triangulation                         #
# ---------------------------------------------------------------------------- #

df <- readRDS(here("data/arms_conjoint.RDS"))

manual_classification <- rio::import(here("data/open_responses_vignette_lr_ger_fr.xlsx")) %>%
  clean_names() %>%
  select(uuid, final_consolidated, h_country) %>%
  rename(hCountry = h_country)


vignette_deont <- df %>%
  select(uuid, hCountry, VIGNETTE, Q17, Choice, pipe_Choice_Pipe, Q18) %>%
  left_join(manual_classification) %>%
  filter(!is.na(final_consolidated)) %>%
  mutate(final_consolidated = case_when(
    final_consolidated == "d" ~ "Fundamental rejection",
    final_consolidated == "c" ~ "Consequentialist rejection",
    final_consolidated == "u" ~ "Unclear",
    final_consolidated == "n" ~ "Illegible"
  )) %>%
  rename(manual_classification = final_consolidated)

# Share illegible
vignette_deont %>%
  count(manual_classification) %>%
  mutate(share = n / sum(n) * 100)

cj_tidy <- conjoint_reshape(df)

cj_tidy <- cj_tidy %>%
  mutate(y_reject = ifelse(y_rating <= 3, 1, 0)) %>%
  mutate(y_reject_strict = ifelse(y_rating == 1, 1, 0)) %>%
  mutate(y_accept = ifelse(y_rating >= 5, 1, 0)) %>%
  group_by(uuid) %>%
  mutate(share_rej = sum(y_reject) / 12) %>%
  mutate(share_rej_strict = sum(y_reject_strict) / 12) %>%
  mutate(share_accept = sum(y_accept) / 12) %>%
  mutate(deont_cj = ifelse(share_rej == 1, 1, 0)) %>%
  mutate(deont_cj_strict = ifelse(share_rej_strict == 1, 1, 0)) %>%
  ungroup() %>%
  mutate(treat_moral = case_when(
    VIGNETTE == 1 ~ "Not democratically elected/Dissidents persecuted/incarcerated/tortured",
    VIGNETTE == 2 ~ "Not democratically elected/Dissidents persecuted/incarcerated/tortured",
    VIGNETTE == 3 ~ "Democratically elected/human rights respected",
    VIGNETTE == 4 ~ "Democratically elected/human rights respected",
    VIGNETTE == 5 ~ "Not democratically elected/Dissidents persecuted/incarcerated/tortured",
    VIGNETTE == 6 ~ "Not democratically elected/Dissidents persecuted/incarcerated/tortured",
    VIGNETTE == 7 ~ "Democratically elected/human rights respected",
    VIGNETTE == 8 ~ "Democratically elected/human rights respected"
  )) %>%
  mutate(treat_econ = case_when(
    VIGNETTE == 1 ~ "1000 million (1 bn)/5000",
    VIGNETTE == 2 ~ "1 Millionen/100",
    VIGNETTE == 3 ~ "1000 million (1 bn)/5000",
    VIGNETTE == 4 ~ "1 Millionen/100",
    VIGNETTE == 5 ~ "1000 million (1 bn)/5000",
    VIGNETTE == 6 ~ "1 Millionen/100",
    VIGNETTE == 7 ~ "1000 million (1 bn)/5000",
    VIGNETTE == 8 ~ "1 Millionen/100",
  )) %>%
  mutate(treat_econ = recode_factor(treat_econ,
    "1 Millionen/100" = "1 Millionen/100",
    "1000 million (1 bn)/5000" = "1000 million (1 bn)/5000"
  )) %>%
  mutate(treat_moral = recode_factor(treat_moral,
    "Not democratically elected/Dissidents persecuted/incarcerated/tortured" = "Not democratically elected/Dissidents persecuted/incarcerated/tortured",
    "Democratically elected/human rights respected" = "Democratically elected/human rights respected"
  )) %>%
  mutate(choice_text = case_when(
    Choice == 1 ~ "Ja, befürworten",
    Choice == 2 ~ "Nein, nicht befürworten"
  ))

cj_tidy %>%
  filter(Choice == 2) %>%
  filter(treat_econ == "1000 million (1 bn)/5000" & treat_moral == "Democratically elected/human rights respected") %>%
  distinct(uuid, deont_cj) %>%
  count(deont_cj)


deont_cj_collapse <- cj_tidy %>%
  distinct(uuid, deont_cj, deont_cj_strict, treat_econ, treat_moral, choice_text, hCountry) %>%
  right_join(vignette_deont) %>%
  filter(uuid != "4hkrzacmaa1gcpbd") # Würde doch befürworten


pos_vignette <- cj_tidy %>%
  distinct(uuid, treat_moral, treat_econ) %>%
  filter(treat_econ == "1000 million (1 bn)/5000" & treat_moral == "Democratically elected/human rights respected") %>%
  n_distinct()

n_deont <- deont_cj_collapse %>%
  filter(treat_econ == "1000 million (1 bn)/5000" & treat_moral == "Democratically elected/human rights respected") %>%
  filter(deont_cj == 1) %>%
  filter(manual_classification == "Fundamental rejection") %>%
  n_distinct()

ui_done("Done cleaning and labelling.")


# ---------------------------------------------------------------------------- #
#                   average support for favorable/unfavorable                  #
# ---------------------------------------------------------------------------- #

ggfun <- function(dat){
  ggp <- ggplot(data = dat, aes(x= y_rating, y=..count../sum(..count..))) +
    scale_y_continuous(expand = c(0,0), limits = c(0,0.5)) +
    geom_histogram(binwidth = 1, color = "grey30", fill = "white") +
    plexi() + labs(x = "Rating", y = "Fraction") +
    theme(legend.position = "none", axis.title.y = element_text(angle = 0, vjust = 0.5)) +
    geom_vline(aes(xintercept = mean(y_rating)), linetype="dotted", col='black', size=1)+
    geom_vline(aes(xintercept = median(y_rating)), linetype="dashed", col='black', size=1)+
    scale_x_continuous(breaks = scales::breaks_pretty(n=7), limits = c(0.5, 7.5), 
                       labels = c("", "1 \n(reject)", "2", "3", "4", "5", "6", "7 \n(approve)", "")) +
    theme(panel.grid.minor.x = element_blank(), panel.grid.major.y = element_line(), panel.grid.major.x = element_blank())
  
  return(ggp)
}

favorable <- cj_tidy %>% 
  filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 %in% c("Peace in the country", "Conflict with terrorists",
           "Country at war, under attack") &
           ATT4 == "Important partner" & 
           ATT5 == "A lot of trade of goods" & 
           ATT6 %in% c("100 m", 
           "1000 m (1 bn)") &
           ATT7 == "5000" & 
           ATT8 %in% c("Military protective equipment",
           "Military reconnaissance and surveillance systems") &
           ATT9 %in% c("{France/Germany}", "NATO partners (USA, UK, {France/Germany})"))

p <- ggfun(favorable)
p

unfavorable <- cj_tidy %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 %in% c("Freedom of expression suppressed",
                       "Dissidents persecuted/incarcerated/tortured") & 
           ATT3 %in% c("Civil war with rebels", "Country at war, attacks") &
           ATT4 == "Not an important partner" & 
           ATT5 == "Little trade of goods" & 
           ATT6 %in% c("1 m", 
                       "10 m") &
           ATT7 == "100" & 
           ATT8 %in% c("Small arms (e.g. rifles, pistols)",
                       "Large weapons (e.g. tanks, aircraft, ships)") &
           ATT9 %in% c("Unknown", "China and Russia"))

p1 <- ggfun(unfavorable)  
p1

p + scale_y_continuous(limits = c(0,0.35)) + ggtitle("Favorable Package") + p1 + scale_y_continuous(limits = c(0,0.35)) + ggtitle("Unfavorable Package") + labs(y = "")

ggsave(filename = here("figs/fig_3.pdf"), width = 8, height = 5, device = cairo_pdf)


goodgov_goodecon <- cj_tidy %>% 
    filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 %in% c("Peace in the country", "Country at war, under attack") &
           ATT4 %in% c("Important partner", 
                       "Not an important partner")  & 
           ATT5  %in% c("A lot of trade of goods" , 
                        "Little trade of goods" ) & 
           ATT6 %in% c("100 m", 
                       "1000 m (1 bn)") &
           ATT7 == "5000" & 
           ATT8 %in% c("Military protective equipment",
                       "Military reconnaissance and surveillance systems") &
           ATT9 %in% c("{France/Germany}", "NATO partners (USA, UK, {France/Germany})", "Unknown", "China and Russia"))


p_ggge_de <- goodgov_goodecon %>%  filter(hCountry == "Germany") %>% ggfun(.) 
p_ggge_de

p_ggge_fr <- goodgov_goodecon %>%  filter(hCountry == "France") %>% ggfun(.)  
p_ggge_fr


goodgov_badecon <- cj_tidy %>% 
    filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 %in% c("Peace in the country", "Country at war, under attack") &
           ATT4 %in% c("Important partner", 
                       "Not an important partner")  & 
           ATT5  %in% c("A lot of trade of goods" , 
                        "Little trade of goods" ) & 
           ATT6 %in% c("1 m", 
                       "10 m") &
           ATT7 == "100" & 
           ATT8 %in% c("Military protective equipment",
                       "Military reconnaissance and surveillance systems") &
           ATT9 %in% c("{France/Germany}", "NATO partners (USA, UK, {France/Germany})", "Unknown", "China and Russia"))


p_ggbe_de <- goodgov_badecon %>%  filter(hCountry == "Germany") %>% ggfun(.)  
p_ggbe_de

p_ggbe_fr <- goodgov_badecon %>%  filter(hCountry == "France") %>% ggfun(.)  
p_ggbe_fr

badgov_badecon <- cj_tidy %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 %in% c("Dissidents persecuted/incarcerated/tortured") & 
           ATT3 %in% c("Country at war, attacks") &
           ATT4 %in% c("Important partner", 
                       "Not an important partner")  & 
           ATT5  %in% c("A lot of trade of goods" , 
                        "Little trade of goods" ) & 
           ATT6 %in% c("1 m", 
                       "10 m") &
           ATT7 == "100" & 
           ATT8 %in% c("Small arms (e.g. rifles, pistols)",
                       "Large weapons (e.g. tanks, aircraft, ships)") &
           ATT9 %in% c("{France/Germany}", "NATO partners (USA, UK, {France/Germany})", "Unknown", "China and Russia"))


p_bgbe_de <- badgov_badecon %>%  filter(hCountry == "Germany") %>% ggfun(.)  
p_bgbe_de

p_bgbe_fr <- badgov_badecon %>%  filter(hCountry == "France") %>% ggfun(.)  
p_bgbe_fr

badgov_goodecon <- cj_tidy %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 %in% c("Dissidents persecuted/incarcerated/tortured") & 
           ATT3 %in% c("Country at war, attacks") &
           ATT4 %in% c("Important partner", 
                       "Not an important partner")  & 
           ATT5  %in% c("A lot of trade of goods" , 
                        "Little trade of goods" ) & 
           ATT6 %in% c("100 m", 
                       "1000 m (1 bn)") &
           ATT7 == "5000" & 
           ATT8 %in% c("Small arms (e.g. rifles, pistols)",
                       "Large weapons (e.g. tanks, aircraft, ships)") &
           ATT9 %in% c("{France/Germany}", "NATO partners (USA, UK, {France/Germany})", "Unknown", "China and Russia"))

p_bgge_de <- badgov_goodecon %>%  filter(hCountry == "Germany") %>% ggfun(.)  
p_bgge_de

p_bgge_fr <- badgov_goodecon %>%  filter(hCountry == "France") %>% ggfun(.)  
p_bgge_fr


axis2 = theme(axis.text.y = element_blank(),
             axis.ticks.y = element_blank(),
             axis.title.y = element_blank(), 
             axis.title.x = element_blank())

axis1 = theme(axis.title.x = element_blank())

p1 <- (p_bgbe_de + axis1 | p_bgbe_fr + axis2) + 
  plot_annotation(title = "Germany                                       France\n", subtitle = "Low value, bad governance", 
                  theme = plexi(plot.subtitle = element_text(hjust = 0.5),
                                plot.title = element_text(hjust = 0.6)))
p1

p2 <- (p_bgge_de + axis1 | p_bgge_fr + axis2) + 
  plot_annotation(subtitle = "High value, bad governance", 
                  theme = plexi(plot.subtitle = element_text(hjust = 0.5)))
p2

p3 <- (p_ggbe_de + axis1 | p_ggbe_fr + axis2) + 
  plot_annotation(subtitle = "Low value, good governance", 
                  theme = plexi(plot.subtitle = element_text(hjust = 0.5)))

p4 <- (p_ggge_de  | p_ggge_fr + theme(axis.text.y = element_blank(),
                                 axis.ticks.y = element_blank(),
                                 axis.title.y = element_blank())) + 
  plot_annotation(subtitle = "High value, good governance", 
                  theme = plexi(plot.subtitle = element_text(hjust = 0.5)))

plot_grid(p1, p2, p3, p4, align = "v", nrow = 4)

ggsave(filename = here("figs/fig_a_12.pdf"), width = 8, height = 10, device = cairo_pdf)

# ---------------------------------------------------------------------------- #
#                          deontologist triangulation                          #
# ---------------------------------------------------------------------------- #

ui_todo("Creating Tables and figures for the deontologist triangulation.")

tab <- deont_cj_collapse %>%
  filter(treat_econ == "1000 million (1 bn)/5000" & treat_moral == "Democratically elected/human rights respected") %>%
  filter(deont_cj == 1) %>%
  group_by(manual_classification, hCountry) %>%
  summarise(n = n()) %>%
  group_by(hCountry) %>%
  mutate(Percent = n / sum(n)) %>%
  arrange(-Percent) %>%
  rename(`Classification of open response` = manual_classification, Country = hCountry) %>%
  gt() %>%
  fmt_percent(Percent) %>%
  summary_rows(
    groups = TRUE,
    columns = c(n),
    fns = list(
      Total = "sum"
    ),
    formatter = fmt_number,
    decimals = 0
  ) %>%
  summary_rows(
    groups = TRUE,
    columns = c(Percent),
    fns = list(
      Total = "sum"
    ),
    formatter = fmt_percent,
    decimals = 2
  ) %>%
  tab_header("Classification of open text answers for deontologists* who saw a positive vignette.") %>%
  tab_source_note("*Here defined as respondents who had a maximum rating of 3 on all conjoint tasks
and rejected the additional vignette. That is, 247/1654 = 14.93% of respondents who saw a positive vignette. Hence, open
responses would suggest a lower bound of 188/1654 = 11.37% deontological respondents.")

gtsave(tab, "table_2.tex", path = here("tabs/"))

# ------------------------------------ Q20 ----------------------------------- #

deonts <- deont_cj_collapse %>%
  filter(deont_cj == 1)


deonts_otherqs <- deonts %>%
  select(uuid, manual_classification, treat_moral, treat_econ, choice_text, hCountry) %>%
  left_join(df %>% select(uuid, Q19r1, Q20C, Q20D, Q20E, Q20F, Q21r6, Q21r7, Q21r8, Q21r9, Q21r10))

setDT(deonts_otherqs)
attr_names <- c("Q20C", "Q20D", "Q20E", "Q20F", "Q19r1", "Q21r6", "Q21r7", "Q21r8", "Q21r9", "Q21r10")
deonts_otherqs[, (attr_names) := lapply(.SD, factor), .SDcols = attr_names]
deonts_otherqs <- data.frame(deonts_otherqs)

lik <- deonts_otherqs %>%
  select(Q20C, Q20D, Q20E, Q20F)

levels(lik$Q20C)
levels(lik$Q20D)
levels(lik$Q20E)
levels(lik$Q20F)

names(lik) <- c(
  Q20C = "Should arms transfers be much more restricted or much less retricted than they are now?",
  Q20D = "Under certain conditions, arms deliveries are necessary to help a country repel an enemy or maintain security in the country.",
  Q20E = "The trade or transfer of weapons between countries should not be permitted as a matter of principle.*",
  Q20F = "A country should trade arms if it benefits its economy, no matter what the other effects of that trade are."
)

sapply(lik, function(x) {
  length(levels(x))
}) # The number of levels in each factor

mylevels <- c("1", "2", "3", "4", "5", "6", "7")

# Here we will recode each factor and explicitly set the levels
for (i in seq_along(lik)) {
  lik[, i] <- factor(lik[, i], levels = mylevels)
}

lik2 <- lik %>%
  select(-"Should arms transfers be much more restricted or much less retricted than they are now?") %>%
  likert()


p1 <- plot(lik2, centered = T, wrap.labels = 100) + plexi() +
  scale_fill_manual(
    values = c("#d73027", "#dc7767", "#f5b294", "#d8d4d4", "#A2CDE3", "#5EA3CB", "#417CB8"),
    labels = c(
      "(1)\n Strongly disagree",
      "(2)",
      "(3)",
      "(4) Neither/nor",
      "(5)",
      "(6)",
      "(7)\n Strongly dgree"
    )
  ) +
  theme(
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    legend.position = "bottom", legend.title = element_blank(), legend.title.align = 0
  ) +
  guides(fill = guide_legend(label.position = "bottom", nrow = 1, override.aes = list(size = 1))) +
  theme(text = element_text(size = 20), legend.text = element_text(size = 10), plot.title = element_text(size = 20, margin = margin(0.5, 0.5, 0.5, 0.5, "cm"))) +
  ggtitle("Generally speaking, what is your position on the following statements...") + labs(y = "Percentage") + theme(legend.key.width = unit(1.75, "cm"))
p1


lik3 <- lik %>%
  select("Should arms transfers be much more restricted or much less retricted than they are now?") %>%
  likert()


p2 <- plot(lik3, centered = T, wrap.labels = 100) + plexi() +
  scale_fill_manual(
    values = c("#d73027", "#dc7767", "#f5b294", "#d8d4d4", "#A2CDE3", "#5EA3CB", "#417CB8"),
    labels = c(
      "(1)\n Much more",
      "(2)",
      "(3)",
      "(4)",
      "(5)",
      "(6)",
      "(7)\n Much less"
    )
  ) +
  theme(
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    legend.position = "bottom", legend.title = element_blank(), legend.title.align = 0
  ) +
  guides(fill = guide_legend(label.position = "bottom", nrow = 1, override.aes = list(size = 1))) +
  theme(text = element_text(size = 20), legend.text = element_text(size = 10), plot.title = element_text(size = 20, margin = margin(0.5, 0.5, 0.5, 0.5, "cm"))) +
  theme(legend.key.width = unit(1.75, "cm"))
p2

p_comb <- p1 + p2 + plot_layout(ncol = 1, heights = c(4.5, 1))

ggsave(p_comb, filename = here("figs/fig_4b.pdf"), width = 15, height = 8, device = cairo_pdf)

# ------------------------------------ Q19 ----------------------------------- #

lik <- deonts_otherqs %>%
  select(Q19r1)

levels(lik$Q19r1)

names(lik) <- c(
  Q19r1 = "... bad for moral reasons"
)

sapply(lik, function(x) {
  length(levels(x))
}) # The number of levels in each factor

mylevels <- c("1", "2", "3", "4", "5", "6", "7")

# Here we will recode each factor and explicitly set the levels
for (i in seq_along(lik)) {
  lik[, i] <- factor(lik[, i], levels = mylevels)
}

lik2 <- lik %>% likert()


p1 <- plot(lik2, centered = T, wrap.labels = 100) + plexi() +
  scale_fill_manual(
    values = c("#d73027", "#dc7767", "#f5b294", "#d8d4d4", "#A2CDE3", "#5EA3CB", "#417CB8"),
    labels = c(
      "(1)\n Much more",
      "(2)",
      "(3)",
      "(4)",
      "(5)",
      "(6)",
      "(7)\n Much less"
    )
  ) +
  theme(
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    legend.position = "bottom", legend.title = element_blank(), legend.title.align = 0
  ) +
  guides(fill = guide_legend(label.position = "bottom", nrow = 1, override.aes = list(size = 1))) +
  theme(text = element_text(size = 20), legend.text = element_text(size = 10), plot.title = element_text(size = 20, margin = margin(0.5, 0.5, 0.5, 0.5, "cm"))) +
  ggtitle("This arms delivery is...") + labs(y = "Percentage") + theme(legend.key.width = unit(1.75, "cm"))
p1

ggsave(p1, filename = here("figs/fig_4a.pdf"), width = 12, height = 3, device = cairo_pdf)

# ------------------------------------ Q21 - war ----------------------------------- #

lik <- deonts_otherqs %>%
  select(Q21r6, Q21r7, Q21r8, Q21r9, Q21r10)

levels(lik$Q21r6)

names(lik) <- c(
  Q21r6 = "There is no conceivable justification for war.",
  Q21r7 = "War is sometimes
the best way to resolve a
conflict.",
  Q21r8 = "War is a
futile struggle
that leads to
self-destruction",
  Q21r9 = "Under certain conditions, war is necessary for the maintenance of justice.",
  Q21r10 = "Although war
is terrible, it has
has a certain
value."
)

sapply(lik, function(x) {
  length(levels(x))
}) # The number of levels in each factor

mylevels <- c("1", "2", "3", "4", "5", "6", "7")

# Here we will recode each factor and explicitly set the levels
for (i in seq_along(lik)) {
  lik[, i] <- factor(lik[, i], levels = mylevels)
}

lik2 <- lik %>% likert()


p1 <- plot(lik2, centered = T, wrap.labels = 100) + plexi() +
  scale_fill_manual(
    values = c("#d73027", "#dc7767", "#f5b294", "#d8d4d4", "#A2CDE3", "#5EA3CB", "#417CB8"),
    labels = c(
      "(1)\n Strongly disagree",
      "(2)",
      "(3)",
      "(4) Neither/nor",
      "(5)",
      "(6)",
      "(7)\n Strongly dgree"
    )
  ) +
  theme(
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    legend.position = "bottom", legend.title = element_blank(), legend.title.align = 0
  ) +
  guides(fill = guide_legend(label.position = "bottom", nrow = 1, override.aes = list(size = 1))) +
  theme(text = element_text(size = 20), legend.text = element_text(size = 10), plot.title = element_text(size = 20, margin = margin(0.5, 0.5, 0.5, 0.5, "cm"))) +
  ggtitle("Please read the following sentences and indicate your agreement or disagreement \n on a scale of 1 ('strongly disagree') to 7 ('strongly agree').") + labs(y = "Percentage") + theme(legend.key.width = unit(1.75, "cm"))
p1

ggsave(p1, filename = here("figs/fig_a_3.pdf"), width = 18, height = 8, device = cairo_pdf)

ui_done("Done creating Tables and figures for the deontologist triangulation.")

# ----------------------------- sample sentences ----------------------------- #

set.seed(777)

sentences <- manual_classification %>%
  left_join(df %>% select(uuid, Q18)) %>%
  left_join(cj_tidy %>% select(uuid, treat_econ, treat_moral)) %>%
  distinct(uuid, Q18, treat_econ, treat_moral, final_consolidated, hCountry) %>%
  filter(treat_econ == "1000 million (1 bn)/5000" & treat_moral == "Democratically elected/human rights respected") %>%
  filter(final_consolidated %in% c("d", "c", "u")) %>%
  group_by(final_consolidated) %>%
  sample_n(10) %>%
  filter(uuid %in% c(
    "8fpccspks57nuv92",
    "v4kq10xsu8gbf2pe",
    "nn1czkaswznnkp6a",
    "m6t86h8z9vt63mrx",
    "jzhumn7rvcrs9puw",
    "f71ta6f0d1rzedtp",
    "s4tb36pravysfkcf",
    "v73x9qhnttnx7bkm",
    "bv9p57tbsmkhk0j2"
  )) %>%
  mutate(final_consolidated = case_when(
    final_consolidated == "d" ~ "Fundamental rejection",
    final_consolidated == "c" ~ "Consequentialist rejection",
    final_consolidated == "u" ~ "Unclear",
    final_consolidated == "n" ~ "Illegible"
  )) %>%
  select(final_consolidated, Q18) %>%
  mutate(Translation = NA) %>%
  gt() %>%
  tab_header("Exemplary open responses to the additional vignette and the respective classification")


gtsave(sentences, "table_a_4.tex", path = here("tabs/"))

ui_done("Created examplary sentences of manual classification.")

# ----------------------------------- polls ---------------------------------- #

polls <- import(here("data/armsexports_polls.xlsx"), skip = 2, col_types = "text") %>%
  select(-timestamp, -institute, -when, -"Date") %>%
  mutate(`Russian invasion` = fct_relevel(as.factor(`Russian invasion`), "Before")) %>%
  mutate(date_end = str_extract(Period, "[0-9]{2}.[0-9]{2}.[0-9]{2}")) %>%
  mutate(date_end = lubridate::dmy(if_else(str_detect(date_end, "20"), str_replace(date_end, "20", "22"), date_end))) %>%
  mutate(id = row_number()) %>%
  mutate(Results = if_else(!is.na(against), "", Results)) %>%
  pivot_longer(cols = c("for", "against", "dont"), values_to = "Percent", names_to = "Segment") %>%
  mutate(Percent = as.numeric(Percent)) %>%
  group_by(id) %>%
  mutate(list_data = list(Percent)) %>%
  ungroup() %>%
  select(-Segment, -Percent) %>%
  distinct() %>%
  arrange(date_end, `Russian invasion`) %>%
  select(-date_end, -id, -Results) %>%
  relocate(Link, .after = last_col()) %>%
  gt() %>%
  gt_plt_bar_stack(
    column = list_data,
    labels = c("In Favor", "Against", "Don't Know"),
    palette = c("#00880b", "#810202", "#bfbfbf")
  ) %>%
  opt_table_font(
    font = "CMU Serif"
  ) %>%
  tab_options(
    table_body.hlines.color = "#ffffff", table_body.border.bottom.color = "#000000", column_labels.border.bottom.color = "#000000",
    column_labels.border.top.color = "#ffffff"
  )

gtsave(polls, "fig_a_1.html", path = here("figs/"))

ui_done("Created table of external polls.")

# --------------------------- electoral importance --------------------------- #

pos_vignette2 <- cj_tidy %>%
  distinct(uuid, Q13, Q13_FR, ParteDisplay_DE, ParteDisplay_FR, Q20B, Q20A)

deont_importance <- deont_cj_collapse %>%
  filter(deont_cj == 1) %>%
  select(uuid, deont_cj) %>%
  right_join(pos_vignette2) %>%
  mutate(rejectors = if_else(is.na(deont_cj), 0, deont_cj)) %>%
  mutate(`same party` = if_else((ParteDisplay_DE == Q13 & Q13 < 7) | (ParteDisplay_FR == Q13_FR & Q13_FR < 9), 1, 0)) %>%
  mutate(`same party` = if_else(is.na(`same party`), 0, `same party`))


deont_importance_strict <- deont_cj_collapse %>%
  filter(deont_cj_strict == 1 & manual_classification == "Fundamental rejection") %>%
  select(uuid, deont_cj_strict) %>%
  right_join(pos_vignette2) %>%
  mutate(deontologists = if_else(is.na(deont_cj_strict), 0, deont_cj_strict)) %>%
  mutate(`same party` = if_else((ParteDisplay_DE == Q13 & Q13 < 7) | (ParteDisplay_FR == Q13_FR & Q13_FR < 9), 1, 0)) %>%
  mutate(`same party` = if_else(is.na(`same party`), 0, `same party`))

models <- list(
  "Rejectors" = lm(Q20B ~ `same party` + rejectors, deont_importance),
  "Deontologists" = lm(Q20B ~ `same party` + rejectors, deont_importance),
  "Rejectors" = lm(Q20B ~ `same party` * rejectors, deont_importance),
  "Deontologists" = lm(Q20B ~ `same party` * deontologists, deont_importance_strict)
)

modelsummary(models, output = here("tabs/tab_a_6.tex"))

ui_done("Created electoral importance regression tables.")

# --------------------------------- party ID --------------------------------- #

party_x_rej_de <- cj_tidy %>%
  filter(hCountry == "Germany") %>%
  distinct(uuid, deont_cj, deont_cj_strict, treat_econ, treat_moral, choice_text, hCountry, Q13, Q13_FR) %>%
  left_join(vignette_deont) %>%
  mutate(rejectors = if_else(deont_cj == 1 & !is.na(Choice), "n rejectors (w/ maxraiting = 3)", "n not a rejector (w/ maxraiting = 3)")) %>%
  mutate(party = factor(case_when(
    Q13 == 1 ~ "CDU/CSU",
    Q13 == 2 ~ "SPD",
    Q13 == 3 ~ "Grüne",
    Q13 == 4 ~ "DIE LINKE",
    Q13 == 5 ~ "FDP",
    Q13 == 6 ~ "AfD",
    Q13 == 7 ~ "Others",
    Q13 == 8 ~ "N/A"
  ), levels = c(
    "AfD",
    "CDU/CSU",
    "DIE LINKE",
    "FDP",
    "Grüne",
    "SPD",
    "N/A",
    "Others"
  ))) %>%
  rename(`Rejectors` = rejectors, `Vote Intention` = party, Country = hCountry) %>%
  tbl_cross(`Vote Intention`, `Rejectors`, percent = "row") %>%
  as_gt()

party_x_rej_fr <- cj_tidy %>%
  filter(hCountry == "France") %>%
  distinct(uuid, deont_cj, deont_cj_strict, treat_econ, treat_moral, choice_text, hCountry, Q13, Q13_FR) %>%
  left_join(vignette_deont) %>%
  mutate(rejectors = if_else(deont_cj == 1 & !is.na(Choice), "n rejectors (w/ maxraiting = 3)", "n not a rejector (w/ maxraiting = 3)")) %>%
  mutate(party = factor(case_when(
    Q13_FR == 1 ~ "Rassemblement national", Q13_FR == 2 ~ "La République en marche", Q13_FR == 3 ~ "Europe Ecologie - Les Verts", Q13_FR == 4 ~ "Les Républicains",
    Q13_FR == 5 ~ "La France insoumise de Jean-Luc Mélenchon",
    Q13_FR == 6 ~ "Parti socialiste",
    Q13_FR == 7 ~ "Debout la France",
    Q13_FR == 8 ~ "Parti communiste français",
    Q13_FR == 9 ~ "Others",
    Q13_FR == 10 ~ "N/A"
  ), levels = c(
    "Debout la France",
    "Europe Ecologie - Les Verts",
    "La France insoumise de Jean-Luc Mélenchon",
    "La République en marche",
    "Les Républicains",
    "Parti communiste français",
    "Parti socialiste",
    "Rassemblement national",
    "N/A",
    "Others"
  ))) %>%
  rename(`Rejectors` = rejectors, `Vote Intention` = party, Country = hCountry) %>%
  tbl_cross(`Vote Intention`, `Rejectors`, percent = "row") %>%
  as_gt()

gtsave(party_x_rej_de, "tab_a_7.tex", path = here("tabs/"))
gtsave(party_x_rej_fr, "tab_a_8.tex", path = here("tabs/"))

ui_done("Created PartyID table.")

}